package com.tengfei.sharedpreferencesdemo;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

    private EditText mEt_1;
    private EditText mEt_2;
    private Button mBt_1;
    private Button mBt_2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        SharedPreferences spf1 = PreferenceManager.getDefaultSharedPreferences(this);
        SharedPreferences spf = getSharedPreferences("token", MODE_PRIVATE);

//        // 初始化数据
        init();
//        // 事件处理
        click();
//        SharedPreferences.Editor edit = spf.edit();
//        //存数据
//        edit.putString("token", "my_token");
//        // 提交
//        // 1. 提交到内存中,异步持久化到硬盘
//        edit.apply();
//        // 2. 提交到硬盘中
//        edit.commit();
//
//        // 取数据
//        // 参数一为key，参数二为当key不存在或取不到值的时候的默认值
//        String value = spf.getString("token", "");


    }

    // 事件处理
    private void click() {
        mBt_1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String key = mEt_1.getText().toString().trim();
                String value = mEt_2.getText().toString().trim();
                if (TextUtils.equals(key, "") && TextUtils.equals(value, "")) {
                    Toast.makeText(MainActivity.this, "请输入信息", Toast.LENGTH_SHORT).show();
                } else {
                    SharedPreferences.Editor edit = getSharedPreferences("myShare", MODE_PRIVATE).edit();
                    edit.putString(key, value);
                    edit.apply();
                    Toast.makeText(MainActivity.this, "存入成功", Toast.LENGTH_SHORT).show();
                }
            }
        });
        mBt_2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(MainActivity.this, ShowActivity.class);
                startActivity(intent);

            }
        });
    }

    private void init() {
        mEt_1 = findViewById(R.id.et_1);
        mEt_2 = findViewById(R.id.et_2);
        mBt_1 = findViewById(R.id.bt_1);
        mBt_2 = findViewById(R.id.bt_2);
    }


}





